package com.itheima.service.impl;

import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import com.itheima.mapper.ClazzMapper;
import com.itheima.pojo.Clazz;
import com.itheima.pojo.ClazzQueryParam;
import com.itheima.pojo.PageResult;
import com.itheima.service.ClazzService;
import lombok.RequiredArgsConstructor;
import org.apache.commons.lang3.ObjectUtils;
import org.springframework.stereotype.Service;

import java.time.LocalDate;
import java.time.LocalDateTime;
import java.util.List;

/**
 * 班级业务层
 * @author GY
 * @version V1.0
 * @date 2025-01-09 20:08
 */
@Service
@RequiredArgsConstructor
public class ClazzServiceImpl implements ClazzService {

    private final ClazzMapper clazzMapper;

    @Override
    public PageResult<Clazz> pageQuery(ClazzQueryParam clazzQueryParam) {
        PageHelper.startPage(clazzQueryParam.getPage(), clazzQueryParam.getPageSize());
        Page<Clazz> clazzes = clazzMapper.pageQuery(clazzQueryParam);
        List<Clazz> result = clazzes.getResult();
        result.forEach(v -> {
            LocalDate now = LocalDate.now();
            if(v.getBeginDate().isAfter(now)){
                v.setStatus("未开班");
            } else if(v.getEndDate().isBefore(now)){
                v.setStatus("已结课");
            } else {
                v.setStatus("开班中");
            }
        });
        return new PageResult<> (clazzes.getTotal(),result);
    }

    @Override
    public void save(Clazz clazz) {
        clazz.setCreateTime(LocalDateTime.now());
        clazzMapper.insert(clazz);
    }

    /**
     * 查询所有
     */
    @Override
    public List<Clazz> findAll() {
        return clazzMapper.findAll();
    }

    /**
     * 删除
     */
    @Override
    public void delete(Integer id) {
        if (ObjectUtils.isEmpty(id)){
            throw new RuntimeException("ClazzDelete : Param Error");
        }
         clazzMapper.delete(id);
    }

    /**
     * 添加
     */
    @Override
    public void insert(Clazz clazz) {
        clazz.setCreateTime(LocalDateTime.now());
        clazz.setUpdateTime(LocalDateTime.now());
        clazzMapper.insert(clazz);
    }

    /**
     * 通过ID查询
     * @param id
     * @return
     */
    public Clazz findById(Integer id) {
        return clazzMapper.findById(id);

    }

    /**
     * 更新
     * @param clazz
     */
    @Override
    public void update(Clazz clazz) {
        clazz.setUpdateTime(LocalDateTime.now());
        clazzMapper.update(clazz);

    }
}
